package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.company.entity.*;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.admin.company.service.TaskEntityService;
import com.fz.us.admin.dict.entity.DictItem;
import com.fz.us.admin.dict.service.DictItemService;
import com.fz.us.oa.core.entity.com.PersonnelInfo;
import com.fz.us.oa.core.entity.com.PersonnelSelf;
import com.fz.us.oa.core.service.com.PersonnelInfoService;
import com.fz.us.oa.core.service.com.PersonnelSelfService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/7/17.
 */
@Controller
@RequestMapping(value = "/com/personnelSelf")
public class PersonnelSelfController extends BaseController {
    private static final long serialVersionUID = -6778264740474090216L;

    @Autowired
    private PersonnelSelfService personnelSelfService;
    @Autowired
    private PersonnelInfoService personnelInfoService;
    @Autowired
    private DictItemService dictItemService;
    @Autowired
    private TaskEntityService taskEntityService;
    @Autowired
    private DutyService dutyService;


    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String parentId,String draft,String index,String todo,String remind,String record) {
        ArrayList<DictItem> eduDictItems = getDictItems(user,"education");
        if (StringUtils.isNotEmpty(keyId)){
            PersonnelSelf personnelSelf=personnelSelfService.get(keyId);
            model.addAttribute("keyId", keyId);
            model.addAttribute("personnelSelf", personnelSelf);
        }
        model.addAttribute("parentId", parentId);
        model.addAttribute("eduDictItems",eduDictItems);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/personnelSelf_input";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if(StringUtils.isNotEmpty(keyId)) {
            PersonnelSelf personnelSelf=personnelSelfService.get(keyId);
            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
            int stepNo = taskEntity.getStepNo();
            String isEdit =  isEdit(keyId);
            model.addAttribute("isEdit", isEdit);
            model.addAttribute("personnelSelf", personnelSelf);
            model.addAttribute("stepNo", stepNo);
        }
        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/personnelSelf_read";
    }

    /**
     * 保存Model数据
     */
    private PersonnelSelf saveModel(User user, String keyId, String birthday, String placeOrigin,String nation,
                                    String address, String urgentPerson, String urgentPhone, String registeredResidence,
                                    String residencePermit, String reDateStart, String reDateEnd, String marry,
                                    String educationId, String school, String family,String parentId) throws ParseException {

        PersonnelSelf personnelSelf = null;
        if (StringUtils.isBlank(keyId)) {
            personnelSelf = new PersonnelSelf();
            personnelSelf.setCreater(user);
            personnelSelf.setCompany(user.getCompany());
        } else {
            personnelSelf = personnelSelfService.get(keyId);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(StringUtils.isNotEmpty(birthday)){
            personnelSelf.setBirthday(sdf.parse(birthday));
        }
        if(StringUtils.isNotEmpty(placeOrigin)){
            personnelSelf.setPlaceOrigin(placeOrigin);
        }
        if(StringUtils.isNotEmpty(nation)){
            personnelSelf.setNation(nation);
        }
        if(StringUtils.isNotEmpty(address)){
            personnelSelf.setAddress(address);
        }
        if(StringUtils.isNotEmpty(urgentPerson)){
            personnelSelf.setUrgentPerson(urgentPerson);
        }
        if(StringUtils.isNotEmpty(urgentPhone)){
            personnelSelf.setUrgentPhone(urgentPhone);
        }
        if(StringUtils.isNotEmpty(registeredResidence)){
            personnelSelf.setRegisteredResidence(Integer.parseInt(registeredResidence));
        }
        if(StringUtils.isNotEmpty(residencePermit)){
            personnelSelf.setResidencePermit(Integer.parseInt(residencePermit));
        }
        if(StringUtils.isNotEmpty(reDateStart)){
            personnelSelf.setReDateStart(sdf.parse(reDateStart));
        }
        if(StringUtils.isNotEmpty(reDateEnd)){
            personnelSelf.setReDateEnd(sdf.parse(reDateEnd));
        }
        if(StringUtils.isNotEmpty(marry)){
            personnelSelf.setMarry(Integer.parseInt(marry));
        }
        if(StringUtils.isNotEmpty(educationId)){
            personnelSelf.setEducation(dictItemService.get(educationId));
        }
        if(StringUtils.isNotEmpty(school)){
            personnelSelf.setSchool(school);
        }
        if(StringUtils.isNotEmpty(family)){
            personnelSelf.setFamily(family);
        }
        if(StringUtils.isNotEmpty(parentId)){
            personnelSelf.setPersonnelInfo(personnelInfoService.get(parentId));
        }
        personnelSelf.setName("名字居然不能为空...");

        String personnelUserString="";
        Set<Duty> dutySet=personnelInfoService.get(parentId).getUser().getDutySet();
        for(Duty duty:dutySet){
            Department department=duty.getPower().getDepartment().getParent()==null?duty.getPower().getDepartment():duty.getPower().getDepartment().getParent();
            for(Department dept:department.getChildren()){
                Set<Power> powerSet=dept.getPowerSet();
                for(Power power:powerSet){
                    if(power.getPost().getName().equals("人事专员")){
                        List<User> usersList=dutyService.getPersons(dept,power.getPost());
                        for(User user1:usersList){
                            personnelUserString+=user1.getId()+",";
                        }
                    }
                }
            }
        }
        personnelSelf.setPersonnelUserString(personnelUserString);
        personnelSelf.setUserId(personnelInfoService.get(parentId).getUser().getId());

        return personnelSelf;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user,
                       @RequestParam(required = false) String keyId,
                       String birthday,
                       String placeOrigin,
                       String nation,
                       String address,
                       String urgentPerson,
                       String urgentPhone,
                       String registeredResidence,
                       String residencePermit,
                       String reDateStart,
                       String reDateEnd,
                       String marry,
                       String educationId,
                       String school,
                       String family,
                       String parentId) throws ParseException {

        Map<String,Object> rMap=new HashMap<String,Object>();
        PersonnelSelf personnelSelf = saveModel(user, keyId, birthday, placeOrigin, nation, address, urgentPerson, urgentPhone, registeredResidence,
                residencePermit, reDateStart, reDateEnd, marry, educationId, school, family, parentId);

        if(StringUtils.isNotEmpty(keyId)){
            personnelSelfService.update(personnelSelf);
            rMap.put("message", "更新成功");
        } else {
            personnelSelfService.save(personnelSelf, "com.fz.us.oa.core.entity.com.PersonnelSelf");
            rMap.put("message", "保存成功");
        }
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 提交操作
     */
    @RequestMapping(value = "submit", method = RequestMethod.POST)
    public Object submit(@CurrentUser User user,
                         @RequestParam(required = false) String keyId,
                         String birthday,
                         String placeOrigin,
                         String nation,
                         String address,
                         String urgentPerson,
                         String urgentPhone,
                         String registeredResidence,
                         String residencePermit,
                         String reDateStart,
                         String reDateEnd,
                         String marry,
                         String educationId,
                         String school,
                         String family,
                         String parentId,
                         String curDutyId,
                         String comment) throws ParseException {

        Map<String, Object> rMap = new HashMap<String, Object>();
        PersonnelSelf personnelSelf = saveModel(user, keyId, birthday, placeOrigin, nation, address, urgentPerson, urgentPhone, registeredResidence,
                residencePermit, reDateStart, reDateEnd, marry, educationId, school, family, parentId);

        if (StringUtils.isNotEmpty(keyId)) {
            personnelSelfService.approve(personnelSelf, dutyService.get(curDutyId), comment);
        } else {
            personnelSelfService.commit(personnelSelf, "com.fz.us.oa.core.entity.com.PersonnelSelf", dutyService.get(curDutyId));
        }

        if(personnelSelf.getProcessState().name().equals("Finished")){
            doFinished(personnelSelf,parentId);
        }

        rMap.put("message", "提交成功");
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String curDutyId, String comment, String parentId){
        Map<String,Object> rMap=new HashMap<String,Object>();
        PersonnelSelf personnelSelf = personnelSelfService.get(keyId);
        personnelSelfService.approve(personnelSelf, dutyService.get(curDutyId), comment);

        //归档后设置和主表的关系
        if(personnelSelf.getProcessState().name().equals("Finished")){
            doFinished(personnelSelf,parentId);
        }
        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    public void doFinished(PersonnelSelf personnelSelf,String parentId){
        PersonnelInfo personnelInfo=personnelInfoService.get(parentId);
        personnelInfo.setPersonnelSelf(personnelSelf);
        personnelInfo.setMonth(Integer.parseInt(DataUtil.DateToString(personnelSelf.getBirthday(), "MM")));
        personnelInfoService.update(personnelInfo);
    }

    /**
     * 退回
     * @return
     */
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            PersonnelSelf personnelSelf = personnelSelfService.get(keyId);
            personnelSelfService.back(personnelSelf, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 否决
     * @return
     */
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            PersonnelSelf personnelSelf = personnelSelfService.get(keyId);
            personnelSelfService.deny(personnelSelf, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

}
